const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {
	VueLoaderPlugin
} = require('vue-loader')
const projectBase = require('./build/project.base');


let lastStr = process.argv[process.argv.length - 1];
lastStr = lastStr.toLowerCase(); // 转化成小写
let moduleName = lastStr.replace(/--env=*/g, '');
let isAlone = false;

let setEntry = function() {
	let obj = {};
	let all = {}; //全部模块
	let alone = {}; //单独模块
	for (let key in projectBase) {
		let item = projectBase[key];
		if (item.buildInstruct == moduleName) {
			alone[key] = path.resolve(`.${item.mainJsSrc}`);
			isAlone = true;
		}
		all[key] = path.resolve(`.${item.mainJsSrc}`);
	}
	obj = isAlone && alone || all;
	return obj;
}


let setHtmlPlugin = function() {
	let arr = [];
	let all = []; //全部模块
	let alone = []; //单独模块
	for (let key in projectBase) {
		let item = projectBase[key];
		let htmlObj = {
			template: path.resolve(`.${item.indexHtmlSrc}`),
			filename: `${key}/index.html`,
			chunks: [key],
			hash: true,
		}
		if (key == "index") {
			htmlObj.filename = "index.html";
			alone.push(new HtmlWebpackPlugin(htmlObj));
		}
		if (item.buildInstruct == moduleName) {
			alone.push(new HtmlWebpackPlugin(htmlObj));
		}
		all.push(new HtmlWebpackPlugin(htmlObj));
	}
	arr = isAlone && alone || all;
	return arr;
}


module.exports = {
	// 入口
	entry: {
		// index: __dirname + '/src/public/main.js',
		...setEntry(),
	},
	// 出口
	output: {
		// publicPath: './',
		path: path.resolve(__dirname, 'dist'),
		filename: '[name]/js/[name].[hash:8].bundle.js',
		chunkFilename: '[name].[chunkhash:8].chunk.js',
	},
	// 模块
	module: {
		rules: [{
			test: /\.js$/,
			exclude: /node_modules/, // 忽略第三方的代码
			include: /src/,
			use: {
				loader: 'babel-loader',
				options: {
					presets: ['@babel/preset-env']
				}
			}
		}, {
			test: /\.vue$/,
			use: {
				loader: 'vue-loader',
			},
		}, {
			test: /\.css$/,
			use: ['style-loader', 'css-loader'],
		}, {
			test: /\.scss$/,
			use: ['style-loader', 'css-loader', 'sass-loader']
		}, {
			// test: /\.(png|jpg|gif)$/i,
			test: /\.(png|jpg|gif|jpeg)$/,
			exclude: /node_modules/,
			use: [{
				loader: 'url-loader',
				// loader: 'file-loader',
				options: {
					limit: 2 * 1024, //图片大于limit, 使用file-loader模块进行加载；否则编译成base64字符串形式
					name: '[name].[hash:8].[ext]',
					outputPath: 'assets/img/',
					esModule: false,
					// context: path.resolve(__dirname, 'modules/')
				}
			}, ],
			type: 'javascript/auto'
		}],
	},
	resolve: {
		extensions: ['.js', '.vue', '.json'],
		alias: {
			// 'vue': 'vue/dist/vue.esm.js',
			'@': path.resolve('src'),
			'@admin': path.resolve('src/modules/admin'),
			'@mall': path.resolve('src/modules/mall'),
		}
	},
	// 插件
	plugins: [
		new VueLoaderPlugin(),
		// new HtmlWebpackPlugin({
		// 	template: __dirname + '/src/public/index.html',
		// 	filename: 'index.html',
		// 	chunks: ['index'],
		// 	hash: true,
		// }),
		...setHtmlPlugin(),
	],
}
